import {strongAlert, weakAlert} from "./dialog";
import AMap from 'AMap';
/**
 * @author 张天丰
 * @date 2020/8/20
 * @Description：数据参数处理
 */
const paramDeal = {
  //响应参数处理
  resData({data}) {
    if (data.code === -1) {
      return false
      //weakAlert('请求参数:'+data.code+'请稍后再试！','error');
    } else {
      if (data.data) {
        return data.data
      } else {
        return data
      }
    }
  },
  /**
   * @author 张天丰
   * @date 2020/8/27
   * @Description：参数不能为空
   * @param：str
   * @return：true || false
   */
  param_notNull(str) {
    if (
      str == undefined ||
      typeof str == 'undefined' ||
      !str ||
      str == null ||
      str == '' ||
      /^\s+$/gi.test(str)
    ) {
      return true;
    } else {
      return false;
    }
  },
  /**
   * @author 张天丰
   * @date 2020/8/27
   * @Description：获取对象中空元素
   * @param：Object
   * @return：空元素的key
   */
  obj_nullKey(obj) {
    let nullKey;
    for (let key in obj) {
      if (obj[key]===undefined||obj[key] === null || obj[key] === "" || obj[key] === '') {
        nullKey = key;
      }
    }
    return nullKey;
  },
  /**
   * @author 张天丰
   * @date 2020/8/27
   * @Description：删除对象为空的元素
   * @param：obj
   * @return：obj
   */
  del_objNull(obj) {
    /*for (let prop in obj) {
      obj[prop] === '' ? delete obj[prop] : obj[prop];
    }
    return obj;*/
    for (let key in obj) {
      if (obj[key] === "" || obj[key] === '' || obj[key] === null) {
        obj[key] = undefined;
      }
    }
    return obj;
  },
  /**
   * @author 张天丰
   * @date 2020/8/28
   * @Description：深度克隆对象并把空值转换为null
   * @param：obj
   * @return：新的对象
   */
  obj_clone(obj) {
    let result = Array.isArray(obj) ? [] : {};
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
          result[key] = this.obj_clone(obj[key]);
        } else {
          result[key] = obj[key];
        }
      }
    }
    return result;
    /*let buf;
    if (obj instanceof Array) {
      buf = [];
      let i = obj.length;
      while (i--) {
        buf[i] = this.obj_clone(obj[i]);
      }
      return buf;
    } else if (obj instanceof Object) {
      buf = {};
      for (let key in obj) {
        if (obj[key] === "" || obj[key] === '') {
          obj[key] = null;
        }
        buf[key] = this.obj_clone(obj[key]);
      }
      return buf;
    } else {
      return obj;
    }*/
  },
  /**
   * @author 张天丰
   * @date 2020/8/20
   * @Description：获取数组对象建和值
   * @param：Array 数组对象
   * @return：key value[{id:1,name}]
   */
  arrKey(arr) {
    let key = [];
    arr.forEach((v, i) => {
      key = Object.getOwnPropertyNames(v);
    })
    return key;
  },

  /**
   * @author 张天丰
   * @date 2020/8/27
   * @Description：数组分页
   * @param：
   * @return：
   */
  pagination(pageNo, pageSize, array) {
    let offset = (pageNo - 1) * pageSize;
    return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
  },
  /**
   * @author 张天丰
   * @date 2020/9/2
   * @Description：正则验证
   * @param：str 需要验证的字符串 type 验证类型
   * @return：
   */
  checkStr (str, type) {
    switch (type) {
      case 'phone':  //手机号码
        return /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(16[2|6|7])|(18[0-9])|(17([0-1]|[3]|[5-8]))|(19[1|8|9]))\d{8}$/.test(str);
      case 'tel':   //座机
        return /^((\d{3,4}-\d{7,8})|(\d{7}-\d{1,12})|(\d{8}-\d{1,11})|(\d{11}-\d{1,8})|(\d{7,8})|(\d{11,20})|(\d{3}-\d{8}-\d{1,7})|(\d{3}-\d{7}-\d{1,8})|(\d{4}-\d{7}-\d{1,7})|(\d{4}-\d{8}-\d{1,6}))$/.test(str);
      case 'phoneAll'://座机或手机
        return /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(16[2|6|7])|(18[0-9])|(17([0-1]|[3]|[5-8]))|(19[1|8|9]))\d{8}$|^((\d{3,4}-\d{7,8})|(\d{7}-\d{1,12})|(\d{8}-\d{1,11})|(\d{11}-\d{1,8})|(\d{7,8})|(\d{11,20})|(\d{3}-\d{8}-\d{1,7})|(\d{3}-\d{7}-\d{1,8})|(\d{4}-\d{7}-\d{1,7})|(\d{4}-\d{8}-\d{1,6}))$/.test(str);
      case 'card':  //身份证
        return /*/^\d{15}|\d{18}$/*//^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(str);
      case 'pwd':   //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
        return /^[a-zA-Z]\w{5,17}$/.test(str)
      case 'postal': //邮政编码
        return /[1-9]\d{5}(?!\d)/.test(str);
      case 'QQ':   //QQ号
        return /^[1-9][0-9]{4,9}$/.test(str);
      case 'email':  //邮箱
        return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
      case 'money':  //金额(小数点2位)
        return /^\d*(?:\.\d{0,2})?$/.test(str);
      case 'URL':   //网址
        return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
      case 'IP':   //IP
        return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
      case 'date':  //日期时间
        return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
      case 'number': //数字
        return /^[0-9]$/.test(str);
      case 'english': //英文
        return /^[a-zA-Z]+$/.test(str);
      case 'chinese': //中文
        return /^[\u4E00-\u9FA5]+$/.test(str);
      case 'lower':  //小写
        return /^[a-z]+$/.test(str);
      case 'upper':  //大写
        return /^[A-Z]+$/.test(str);
      case 'HTML':  //HTML标记
        return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
      default:
        return true;
    }
  },
  /*
   * 生日转为年龄（精确到月份）
   */
  birsdayToAge(birsday) {
    let aDate = new Date();
    let thisYear = aDate.getFullYear();
    let bDate = new Date(birsday);
    let brith = bDate.getFullYear();
    let age = thisYear - brith;
    if (aDate.getMonth() == bDate.getMonth()) {
      if (aDate.getDate() < bDate.getDate()) {
        age = age - 1;
      }
    } else {
      if (aDate.getMonth() < bDate.getMonth()) {
        age = age - 1;
      }
    }
    return age;
  },
  /**
   * 节流函数, 用于将多次执行变为每隔一段时间执行
   * @param fn 事件触发的操作
   * @param delay 间隔多少毫秒需要触发一次事件
   */
  throttle2(fn, delay) {
    let timer = null;
    return function () {
      let context = this;
      let args = arguments;
      if (!timer) {
        timer = setTimeout(function () {
          fn.apply(context, args);
          clearTimeout(timer);
        }, delay);
      }
    };
  },
  //请求参数拼接
  params_format(obj) {
    let str = ''
    for (let i in obj) {
      str += i + '=' + obj[i] + '&'
    }
    return str.split('').slice(0, -1).join('')
  },
}
//搜索方法
const $search = {
  /**
   * @author 张天丰
   * @date 2020/9/7
   * @Description：搜索地址返回经纬度
   * @param：city 一级城市名 addr 详细地址
   * @return：Promise经纬度 [121.484705, 31.29421]
   */
  searchLongitude(city,addr){
    return new Promise((resolve,reject)=>{
      new AMap.PlaceSearch({
        pageSize: 1, // 单页显示结果条数
        city:city,//城市一级名
        pageIndex: 1, //页码
        citylimit: true,  //是否强制限制在设置的城市内搜索
      }).search(addr,function (status,result){
        if(status==='complete'){
          let longitude = result.poiList.pois[0].location;
          resolve([longitude.lng,longitude.lat])
        }else{
          reject();
          weakAlert("获取地址经纬度失败，请稍后再试！");
        }
      })
    })
  },

};
/**
 * @author 李炳儒
 * @date 2020/8/21
 * @Description：日期处理
 */
const dateFoment = (function () {
  "use strict";
  /**
   * [String字符串扩展添加format函数]
   * @return {[String]} [返回新的字符串]
   * 用法：
   * "My Name is {0},age is {1}".format('李炳儒',25);
   */
  String.prototype.format = function () {
    let args = arguments;
    return this.replace(/\{(\d+)\}/g, function (s, i) {
      return args[i];
    });
  };

  /**
   * [Date日期添加格式化format函数]
   * @param  {[String]} fmt [格式化字符串]
   * @return {[String]}     [返回格式化后的字符串]
   * 用法:
   * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S")   ==> 2020-07-02 08:09:04.423
   * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss")   ==> 2020-06-10 二 20:09:04
   * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss")  ==> 2020-06-10 周二 08:09:04
   * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2020-06-10 星期二 08:09:04
   * (new Date()).pattern("yyyy-M-d h:m:s.S")        ==> 2020-7-2 8:9:4.18
   */
  Date.prototype.format = function (fmt) {
    let o = {
      "M+": this.getMonth() + 1, //月份
      "d+": this.getDate(), //日
      "h+": this.getHours() % 12 === 0 ? 12 : this.getHours() % 12, //小时
      "H+": this.getHours(), //小时
      "m+": this.getMinutes(), //分
      "s+": this.getSeconds(), //秒
      "q+": Math.floor((this.getMonth() + 3) / 3), //季度
      "S": this.getMilliseconds() //毫秒
    };
    let week = {
      "0": "天",
      "1": "一",
      "2": "二",
      "3": "三",
      "4": "四",
      "5": "五",
      "6": "六"
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay() + ""]);
    }
    for (let k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
    return fmt;
  };

  /**
   * [为数组扩展Append，可以添加数组]
   * @param  {[Array]} otherArray [需要加入的数组]
   * @return {[Array]}            [返回新的数组]
   */
  Array.prototype.append = function (otherArray) {
    otherArray.forEach(function (v) {
      this.push(v);
    }, this);
  };
}());
//货币数字
const moneyRMB = (function () {
  "use strict";
  Number.prototype.formatMoney = function (symbol,places, thousand, decimal) {
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "";//"￥";
    thousand = thousand || ",";
    decimal = decimal || ".";
    let number = this,
      negative = number < 0 ? "-" : "",
      i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
      j = (j = i.length) > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
  }
}())


export
{
  paramDeal,
  $search,
  dateFoment,
  moneyRMB,
}
